import {
  types,
  openFile
} from "@/utils/index";
import conf from "@/common/config/index";
import Storage from "@/common/js/storage";
import qs from "qs";
import {
  mapState
} from "vuex";
export default {
  computed: {
    ...mapState(["pageEdit"]), //此页面信息是否有更改， 为true 时onShow 会重新请求
  },
  data() {
    /* eslint-disable */
    let self = this;
    let typeArr = ["error", "info", "success", "warning"];
    const message = function (opt) {
      if (self.$refs.message) {
        let type = opt.type || "success";
        let index = typeArr.indexOf(type);
        let key = typeArr[index > -1 ? index : 0];
        return self.$refs.message[key](opt);
      } else {
        return new Promise((r, reject) => reject('no ref message'));
      }
    };
    typeArr.forEach((i) => {
      message[i] = message.prototype[i] = function (text) {
        message({
          title: "",
          type: i,
          message: text,
        });
      };
    });
    return {
      dataHeaders: {}, //请求头
      imgSuffixs: ["jpg", "jpeg", "png", "gif"],
      // 设置属性
      mixinViewOptions: {
        createdIsNeed: false, // 此页面是否在创建时，调用查询数据列表接口？
        activatedIsNeed: false, // 此页面是否在激活（进入）时，调用查询数据列表接口？
        getURL: "", // 数据列表接口，API地址
        isPage: false, // 数据列表接口，是否需要分页？
        deleteURL: "", // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        deleteIsBatchKey: "id", // 删除接口，批量状态下由那个key进行标记操作？比如：pid，uid...
        exportURL: "", // 导出接口，API地址
        isShowLoading: false, //是否在请求时显示加载中
        reachBottom: false, //是否在滑动到底部时加载更多
        pullDown: false, //上拉刷新
        ERR_OK: 200, //成功码
        ERR_KEY: "code", //判断是否成功字段
        type: "get", // 请求方式
        deleteType: "post",
        showLoadingTitle: "加载中"
      },
      mixinShareOptions: {
        // 小程序分享配置
        title: "润滑卫士",
        imageUrl: "",
        path: "",
      },
      // 默认属性
      dataForm: {}, // 查询条件
      dataList: [], // 数据列表
      // order: "", // 排序，asc／desc
      // orderField: "", // 排序，字段
      page: 1, // 当前页码
      limit: 10, // 每页数
      total: 0, // 总条数
      dataListLoading: false, // 数据列表，loading状态
      dataListSelections: [], // 数据列表，多选项
      addOrUpdateVisible: false, // 新增／更新，弹窗visible状态
      message,
    };
    /* eslint-enable */
  },
  onLoad() {
    // #ifdef MP
    if (this.mixinViewOptions.share) {
      uni.showShareMenu({
        withShareTicket: true,
        menus: ["shareAppMessage", "shareTimeline"],
      });
    }
    // #endif
    if (this.mixinViewOptions.createdIsNeed) {
      this.getDataList();
    }
  },
  onShow() {
    if (this.mixinViewOptions.activatedIsNeed) {
      this.getDataList();
    }
    if (this.pageEdit) {
      if (this.mixinViewOptions.pullDown) {
        uni.startPullDownRefresh();
      } else {
        this.page = 1;
        this.getDataList();
      }
      this.$store.commit("setPageEdit", false);
    }
  },
  methods: {
    resetInputValue(i, form) {
      if (form[i.key]) {
        if (i.type == "upload") {
          try {
            i.value = form[i.key] ? [data[i.key]] : [];
          } catch (err) {
            i.value = [];
          }
        } else if (i.type == "picker") {
          if (i.mode !== "date" && i.mode !== "datetime") {
            let item = (i.range || []).find((it) => it.value == form[i.key]);
            let index = (i.range || []).findIndex(
              (it) => it.value == form[i.key]
            );
            if (item) {
              i.value = index;
              i.val = item.label;
            }
          } else {
            i.value = form[i.key];
            i.val = form[i.key];
          }
        } else if (i.type == "radio") {
          let arr = form[i.key];
          if (!Array.isArray(arr)) {
            arr = [arr];
          }
          arr.forEach((c) => {
            (i.range || []).forEach((r) => {
              if (r.value == c) {
                r.checked = true;
              }
            });
          });
        } else {
          i.value = form[i.key] || "";
        }
      }
    },
    // 获取数据列表
    getDataList() {
      if (!this.mixinViewOptions.getURL) {
        // uni.showToast({
        //   title: "请传入请求链接!",
        //   icon: "none"
        // })
        return Promise.reject();
      }
      this.dataListLoading = true;
      let isShowLoad = this.mixinViewOptions.isShowLoading;
      if (isShowLoad) {
        uni.showLoading({
          title: this.mixinViewOptions.showLoadingTitle,
        });
      }
      let args = arguments;
      let _config = {
        header: this.dataHeaders || {},
        params: {
          // order: this.order,
          // orderField: this.orderField,
          page: this.mixinViewOptions.isPage ? this.page : null,
          limit: this.mixinViewOptions.isPage ? this.limit : null,
          ...this.dataForm,
        },
      };
      if (this.mixinViewOptions.type !== "get") {
        _config = {
          // order: this.order,
          // orderField: this.orderField,
          page: this.mixinViewOptions.isPage ? this.page : null,
          limit: this.mixinViewOptions.isPage ? this.limit : null,
          ...this.dataForm,
        };
      }
      return this.$http[this.mixinViewOptions.type](
          this.mixinViewOptions.getURL,
          _config,
          this.dataHeaders
        )
        .then((res) => {
          // this.mixinViewOptions.isPage &&
          if (this.page == 1 || this.page == 1) {
            this.dataList.length = 0;
            this.dataList = [];
          }
          this.dataListLoading = false;
          uni.hideLoading();
          if (
            res[this.mixinViewOptions.ERR_KEY] !== this.mixinViewOptions.ERR_OK
          ) {
            let data = [];
            this.fetchComplete(false, data || [], res, ...args);
            this.dataList = this.dataList.concat(data);
            this.total = 0;
            return this.message.error(res.message);
          }
          let data = this.mixinViewOptions.isPage ? res.data.list || res.data.data : res.data;
          let tmp = this.fetchComplete(false, data || [], res, ...args);
          if (tmp) {
            data = tmp;
          }
          this.dataList.push(...data);
          this.total = this.mixinViewOptions.isPage ? res.data.total : 0;
        })
        .catch((err) => {
          uni.hideLoading();
          this.fetchComplete(true, [], err, {});
          this.dataListLoading = false;
        });
    },
    // 多选
    dataListSelectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    fetchComplete(err, data = []) {
      return data;
    },
    // 排序
    dataListSortChangeHandle(data) {
      if (!data.order || !data.prop) {
        this.order = "";
        this.orderField = "";
        return false;
      }
      // this.order = data.order.replace(/ending$/, "");
      // this.orderField = data.prop.replace(/([A-Z])/g, "_$1").toLowerCase();
      this.getDataList();
    },
    // 分页, 每页条数
    pageSizeChangeHandle(val) {
      this.page = 1;
      this.limit = val;
      this.getDataList();
    },
    // 分页, 当前页
    pageCurrentChangeHandle(val) {
      this.page = val;
      this.getDataList();
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.dataForm.id = id;
        this.$refs.addOrUpdate.init();
      });
    },
    // 删除
    deleteHandle(id, option = {}) {
      return new Promise((resolve, reject) => {
        if (this.mixinViewOptions.deleteIsBatch && !id) {
          reject(id);
          return this.message({
            message: "参数不合理!",
            type: "warning",
            duration: 500,
          });
        }
        this.showModal({
            title: "提示",
            content: "确认删除吗?",
            type: "warning",
            ...option,
          })
          .then(() => {
            let data = this.mixinViewOptions.deleteIsBatch ? [id] : {
              id
            };
            // ${
            //   this.mixinViewOptions.deleteIsBatch ? "" : "/" + id
            // }
            this.$http[this.mixinViewOptions.deleteType || "delete"](
                `${this.mixinViewOptions.deleteURL}`,
                data
              )
              .then((res) => {
                if (res.code !== 0) {
                  reject(res);
                  return this.message.error(res.message);
                }
                resolve(res);
                this.message({
                  message: "成功",
                  type: "success",
                  duration: 500,
                  onClose: () => {},
                });
                // this.getDataList();
              })
              .catch(() => {
                reject();
              });
          })
          .catch(() => {
            reject();
          });
      });
    },

    showToast(opt = {}, icon = "none") {
      let def = {
        title: "",
        content: "",
        icon: "none",
        duration: 1500,
      };
      if (typeof opt === "string") {
        opt = {
          title: opt,
          icon,
        };
      }
      let option = Object.assign({}, def, opt);
      return new Promise(function (resolve, reject) {
        uni.showToast({
          ...option,
          success(res) {
            resolve(res);
            if (types.isFunction(option.success)) {
              option.success(res);
            }
          },
          fail(err) {
            reject(err);
            if (types.isFunction(option.fail)) {
              option.fail(err);
            }
          },
          complete() {
            if (types.isFunction(option.complete)) {
              option.complete(...arguments);
            }
          },
        });
      });
    },
    showModal(opt = {}) {
      let def = {
        title: "",
        content: "",
        confirmText: "确认",
        cancelText: "取消",
        showCancel: true,
        confirmColor: "#3F7DFF",
      };
      let option = Object.assign({}, def, opt);
      return new Promise(function (resolve, reject) {
        uni.showModal({
          ...option,
          success(res) {
            resolve(res);
            if (types.isFunction(option.success)) {
              option.success(res);
            }
          },
          fail(err) {
            reject(err);
            if (types.isFunction(option.fail)) {
              option.fail(err);
            }
          },
          complete() {
            if (types.isFunction(option.complete)) {
              option.complete(...arguments);
            }
          },
        });
      });
    },
    // 导出
    exportHandle() {
      var params = qs.stringify({
        token: Storage.get("token"),
        ...this.dataForm,
      });
      // window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewOptions.exportURL}?${params}`
      uni.downloadFile({
        url: `${conf.baseUrl_v1}${this.mixinViewOptions.exportURL}?${params}`,
      });
    },
    onOpenFile: openFile,
  },
  onReachBottom() {
    if (this.mixinViewOptions.reachBottom && this.mixinViewOptions.isPage) {
      if (this.dataList.length < this.total) {
        this.page++;
        this.getDataList();
      }
    }
  },
  async onPullDownRefresh() {
    if (this.mixinViewOptions.pullDown) {
      this.page = 1;
      await this.getDataList();
    }
    uni.stopPullDownRefresh();
  },
  onShareAppMessage() {
    let opt = this.mixinShareOptions;
    if (!opt.path) {
      let pages = getCurrentPages();
      let page = pages[pages.length - 1];
      let path = page.route;
      let op = page.options;
      if (typeof op === "object" && Object.keys(op).length) {
        path += "?" + qs.stringify(op);
      }
      // opt.path = this.$Route.fullPath;
      opt.path = path;
    }
    return opt;
  },
  onShareTimeline() {
    let op = this.mixinShareOptions || {};
    return {
      ...op,
      title: op.title,
      query: this.dataForm,
    };
  },
};